// pages/impression/impression.js
const app = getApp()
const http = require("../../utils/http.js")
const util = require("../../utils/util.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    WindowHeight: app.globalData.WindowHeight,

    endDate: util.getNowDate(new Date()),

    grade: 0,
    content: '',
    imgList: [],
    date: '',
    placeData: {},
    topicData: [],

    version: '1.0.0'
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    http.get("/get")
      .then(res => {
        this.setData({
          version: res.data
        })
      })
  },

  setGrade(e) {
    this.setData({
      grade: e.detail.value
    })
  },
  textareaAInput(e) {
    this.setData({
      content: e.detail.value
    })
  },
  clearTextarea() {
    this.setData({
      content: ''
    })
  },
  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  ChooseImage() {
    wx.chooseImage({
      count: 8, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除这个瞬间吗？',
      cancelText: '考虑一下',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  choosePlaceOrTopic(e) {
    let page = e.currentTarget.dataset.page
    wx.navigateTo({
      url: '/pages/impression/' + page + '/' + page,
    })
  },

  DelTopic(e) {

    wx.showModal({
      title: '提示',
      content: '确定要去掉这个话题吗？',
      cancelText: '考虑一下',
      confirmText: '不用考虑',
      success: res => {
        if (res.confirm) {
          this.data.topicData.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            topicData: this.data.topicData
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1]; //表示当前页面
    //这个是看打印的currPage，发现在__data__中有子页面过来的值
    let placeData = currPage.__data__.placeData;
    delete currPage.__data__['placeData']
    this.setData({
      placeData: placeData
    })

    let topicId = currPage.__data__.topicId;
    let topicTitle = currPage.__data__.topicTitle;
    if (topicTitle == null) {
      return;
    }
    let topic = {
      'id': topicId,
      'topicTitle': topicTitle
    }
    let topicList = this.data.topicData
    
    delete currPage.__data__['topicId']
    delete currPage.__data__['topicTitle']

    for (let i = 0; i < topicList.length; i++) {
      if (JSON.stringify(topic) == JSON.stringify(topicList[i])) {
        wx.showToast({
          title: '不要重复选择哟',
          icon: 'none',
          duration: 2000
        })
        return;
      }
    }
    topicList.push(topic)
    this.setData({
      topicData: topicList
    })

  },

  showToast(text){
    wx.showToast({
      title: text,
      icon: 'none',
      duration: 2000
    })
    return;
  },
  release(e) {
    let self = this
    let impression = {
      grade: self.data.grade,
      content: self.data.content,
      date: self.data.date,
      placeTitle: self.data.placeData.title,
      placeAddress: self.data.placeData.address,
      placeProvince: self.data.placeData.province,
      city: self.data.placeData.city,
      district: self.data.placeData.district
    }
    let text = ''
    if (impression.grade == 0){
      text = "还没有评星哟"
      self.showToast(text);
      return;
    }

    if (impression.content == '' || impression.content == null){
      text = "印象内容不能空着哟"
      self.showToast(text);
      return;
    }

    let imgList = self.data.imgList
    if (imgList.length == 0) {
      text = "还没有选择旅行照片哟"
      self.showToast(text);
      return;
    }

    if (impression.date == '' || impression.date == null){
      text = "还没有选择旅行时间呢"
      self.showToast(text);
      return;
    }

    if (impression.placeTitle == '' || impression.placeTitle == null) {
      text = "还没有选择旅行地点呢"
      self.showToast(text);
      return;
    }

    let fileList = []
    wx.showLoading({
      title: '发布中...',
    })
    for (let i = 0; i < imgList.length; i++) {
      const uploadTask = wx.uploadFile({
        url: http.baseURL + '/file/uploadFile',
        filePath: imgList[i],
        name: 'file',
        success(res) {
          let data = JSON.parse(res.data)
          fileList.push(data.data)
          if (i == imgList.length - 1) {
            let param = {
              impression: impression,
              files: fileList,
              topics: self.data.topicData
            }
            http.post("/impression/insert", {
              param: JSON.stringify(param)
            }).then(res=>{
              wx.hideLoading()
              wx.reLaunch({
                url: '/pages/index/index',
              })
            })
          }
        }
      })
      uploadTask.onProgressUpdate((res) => {
        // console.log('上传进度', res.progress)
        // console.log('已经上传的数据长度', res.totalBytesSent)
        // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})